package com.wn.search.service.impl;

import com.wn.common.utils.Pages;
import com.wn.search.bean.BorrowRecordIndexVo;
import com.wn.search.bean.BorrowRecordSearchQuery;
import com.wn.search.service.ISearchService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.domain.PageRequest;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yellow Docter
 * @date 2024-09-14
 * @desc 蜗牛创想：www.woniuxy.com
 */
@Service
public class SearchServiceImpl implements ISearchService {

    //ES 的api 很多不熟悉  借鉴AI 写
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public Pages<BorrowRecordIndexVo> search(BorrowRecordSearchQuery query) {

        //搜索查询
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 添加查询条件，使用should表示or关系
        if (query.getName() != null) {
            boolQuery.should(QueryBuilders.matchQuery("name", query.getName()));
        }
        if (query.getStartPeriod() != null) {
            boolQuery.should(QueryBuilders.rangeQuery("period").from(query.getStartPeriod()));
        }
        if (query.getEndPeriod() != null) {
            boolQuery.should(QueryBuilders.rangeQuery("period").to(query.getEndPeriod()));
        }
        if (query.getDescription() != null) {
            boolQuery.should(QueryBuilders.matchQuery("description", query.getDescription()));
        }

        // 最少一个条件必须满足
        boolQuery.minimumShouldMatch("1");

        queryBuilder.withQuery(boolQuery);
        // 设置分页
        queryBuilder.withPageable(PageRequest.of(query.getPageNo(), query.getPageSize()));

        //elasticsearchRestTemplate.search 调用
        SearchHits<BorrowRecordIndexVo> searchHits = elasticsearchRestTemplate.search(
                queryBuilder.build(),
                BorrowRecordIndexVo.class);

        List<BorrowRecordIndexVo> list =
                searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList());
        Long totalHits = searchHits.getTotalHits();

        // 返回
        Pages<BorrowRecordIndexVo> pages = new Pages<>();
        pages.setList(list);
        pages.setTotal(totalHits);
        pages.setPageNum(query.getPageNo());
        pages.setPageSize(query.getPageSize());

        return pages;
    }

}
